<script setup lang="ts">
import type { FormRules } from 'element-plus'
import type { AuthAccountModifyPwdCmd } from '@/apis/common/loginApi'
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { loginApi } from '@/apis/common/loginApi'
import { useForm } from '@/composables/useForm'
import BaseCard from '@/layouts/BaseCard.vue'
import { useLoginStore } from '@/stores/loginStore'

const cmd = ref<AuthAccountModifyPwdCmd>({})

const loginStore = useLoginStore()
const router = useRouter()

const { formRef, formLoading, submitForm } = useForm(async () => {
  await loginApi.modifyLoginPwd(cmd.value)
  ElMessage.success('修改密码成功')
  loginStore.logout()
  router.push('/login')
})

const rules = reactive<FormRules<AuthAccountModifyPwdCmd>>({
  newPwd: [
    { required: true, message: '请选择新密码', trigger: ['blur', 'change'] },
    { validator: validateNewPwd, trigger: ['blur', 'change'] },
  ],
  confirmPwd: [
    { required: true, message: '请选择确认密码', trigger: ['blur', 'change'] },
    { validator: validateConfirmPwd, trigger: ['blur', 'change'] },
  ],
})

function validateNewPwd(_: any, value: any, callback: any) {
  if (value && cmd.value.confirmPwd) {
    formRef.value?.validateField('confirmPwd')
    callback()
  }
  else {
    callback()
  }
}

function validateConfirmPwd(_: any, value: any, callback: any) {
  if (value && value !== cmd.value.newPwd) {
    callback(new Error('确认密码与新密码不一致！'))
  }
  else {
    callback()
  }
}
</script>

<template>
  <BaseCard title="修改密码">
    <el-form ref="formRef" :model="cmd" :rules="rules" label-width="100px" class="w-96">
      <el-form-item label="当前密码" prop="oldPwd">
        <el-input v-model="cmd.oldPwd" type="password" />
      </el-form-item>
      <el-form-item label="新密码" prop="newPwd">
        <el-input v-model="cmd.newPwd" type="password" />
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPwd">
        <el-input v-model="cmd.confirmPwd" type="password" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :loading="formLoading" @click="submitForm">
          提交
        </el-button>
      </el-form-item>
    </el-form>
  </BaseCard>
</template>
